package com.tangly.codeing.controller;

import com.tangly.codeing.model.Article;
import com.tangly.codeing.service.EsSearchService;
import com.tangly.codeing.utils.PageInfo;
import com.tangly.codeing.utils.ReturnT;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * elasticsearch 搜索
 *
 * @author tangbing
 * @date 2019/10/31
 */
@RestController
public class EsSearchController {

    private Logger log = LoggerFactory.getLogger(getClass());

    @Resource
    private EsSearchService esSearchService;

    /**
     * 新增 / 修改索引
     */
    @PutMapping("save")
    public String add(@RequestBody Article article) {
        esSearchService.save(article);
        return "success";
    }

    /**
     * 删除索引
     */
    @DeleteMapping("delete/{id}")
    public String delete(@PathVariable String id) {
        esSearchService.delete(id);
        return "success";
    }

    /**
     * 清空索引
     */
    @GetMapping("deleteAll")
    public String deleteAll() {
        esSearchService.deleteAll();
        return "success";
    }

    /**
     * 根据ID获取
     */
    @GetMapping("get/{id}")
    public Article getById(@PathVariable String id) {
        return esSearchService.getById(id);
    }

    /**
     * 根据获取全部
     */
    @GetMapping("getAll")
    public List<Article> getAll() {
        return esSearchService.getAll();
    }

    /**
     * 搜索
     */
    @GetMapping("query/{keyword}")
    public List<Article> query(@PathVariable String keyword) {
        return esSearchService.query(keyword, Article.class);
    }

    /**
     * 搜索，命中关键字高亮
     */
    @PostMapping("queryHitByPage")
    public ReturnT<PageInfo> queryHitByPage(@RequestBody PageInfo pageInfo) {
        // TODO 关键字为空处理待解决
        String keyword = pageInfo.getWhereMap().get("keyword").toString();
        if (StringUtils.equals("", keyword)) {
            pageInfo.setTotalRecord(0);
            pageInfo.setResultObject(esSearchService.getAll());
            return new ReturnT<>(pageInfo);
        }
        return esSearchService.queryHitByPage(pageInfo);
    }

    /**
     * 删除索引库
     */
    @DeleteMapping("deleteIndex/{indexName}")
    public String deleteIndex(@PathVariable String indexName) {
        esSearchService.deleteIndex(indexName);
        return "success";
    }
}
